<?php
class Activity extends AppModel {
    var $validate = array(
        'name' => array(
            'required' => array(
                'required' => true,
                'allowEmpty' => false,
                'rule' => 'notEmpty',
                'message' => 'Wajib diisi',
                'last' => true
            ),
            'maxlength' => array(
                'rule' => array('maxlength', 255),
                'message' => 'Wajib diisi'
            )
        ),
        'position_id' => array(
            'rule' => 'vPosition',
            'message' => 'Pilih sesuai pilihan yang ada'
        )
    );
    
    var $belongsTo = array('Position');
    
    function vPosition($field) {
        return $this->Position->find('count', array(
            'conditions' => array(
                'Position.id' => $field['position_id']
            ),
            'recursive' => -1
        )) > 0;
    }
    
    function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
        $this->Behaviors->attach('Containable');
        $fields = array('id', 'name');
        $contain = array(
            'Position' => array(
                'fields' => 'name'
            )
        );
        $records = $this->find('all', compact(
            'conditions', 'fields', 'order',
            'page', 'recursive', 'group', 'contain'
            )
        );
        $ret = array();
        foreach ( $records as $key => $record ) {
            if ( !isset($ret[ $record['Position']['id'] ]['Activity']) ) {
                $ret[ $record['Position']['id'] ]['Activity']['id'] = $record['Position']['id'];
                $ret[ $record['Position']['id'] ]['Activity']['position'] = $record['Position']['name'];
            }
            
            if ( !isset($ret[ $record['Position']['id'] ]['Act']) ) {
                $ret[ $record['Position']['id'] ]['Act'] = array();
            }
            
            $ret[ $record['Position']['id'] ]['Act'][]  = array(
                'id' => $record['Activity']['id'], 'name' => $record['Activity']['name']
            );
        }
        
        return $ret;
    }
    
    function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
        $sql = "SELECT DISTINCT(position_id) position FROM activities";
        $this->recursive = $recursive;
        $results = $this->query($sql);
        return count($results);
    }
}
?>
